//package com.sctv.scfocus.ui.activities;
//
//import android.Manifest;
//import android.content.Intent;
//import android.content.SharedPreferences;
//import android.content.pm.PackageInfo;
//import android.content.pm.PackageManager;
//import android.os.Build;
//import android.os.Bundle;
//import android.os.Handler;
//import android.preference.PreferenceManager;
//import android.support.annotation.NonNull;
//import android.support.v4.app.ActivityCompat;
//import android.text.TextUtils;
//import android.view.Gravity;
//import android.view.View;
//import android.view.WindowManager;
//import android.widget.ImageView;
//import android.widget.Toast;
//
//import com.jiongbull.jlog.JLog;
//import com.ruihang.generalibrary.ui.dialog.AlertDialogFragment;
//import com.ruihang.generalibrary.ui.util.DefaultTextTimerCallback;
//import com.ruihang.generalibrary.ui.util.TimerViewHelper;
//import com.ruihang.generalibrary.ui.widget.CustomFontTextView;
//import com.ruihang.generalibrary.utils.PermissionUtils;
//import com.letv.app.ljodfh.R;
//import com.letv.app.ljodfh.base.BaseActivity;
//import com.letv.app.ljodfh.beans.LiveAdvanceInfo;
//import com.letv.app.ljodfh.woza.GoCoderSDKPrefs;
//import com.wowza.gocoder.sdk.api.WowzaGoCoder;
//import com.wowza.gocoder.sdk.api.broadcast.WZBroadcast;
//import com.wowza.gocoder.sdk.api.broadcast.WZBroadcastConfig;
//import com.wowza.gocoder.sdk.api.configuration.WZMediaConfig;
//import com.wowza.gocoder.sdk.api.data.WZDataItem;
//import com.wowza.gocoder.sdk.api.data.WZDataMap;
//import com.wowza.gocoder.sdk.api.devices.WZAudioDevice;
//import com.wowza.gocoder.sdk.api.devices.WZCamera;
//import com.wowza.gocoder.sdk.api.devices.WZCameraView;
//import com.wowza.gocoder.sdk.api.errors.WZError;
//import com.wowza.gocoder.sdk.api.errors.WZStreamingError;
//import com.wowza.gocoder.sdk.api.geometry.WZSize;
//import com.wowza.gocoder.sdk.api.graphics.WZColor;
//import com.wowza.gocoder.sdk.api.logging.WZLog;
//import com.wowza.gocoder.sdk.api.status.WZStatus;
//import com.wowza.gocoder.sdk.api.status.WZStatusCallback;
//
//import java.util.ArrayList;
//import java.util.Arrays;
//
//import butterknife.BindView;
//import butterknife.ButterKnife;
//import butterknife.OnClick;
//
//public class StreamLiveActivity extends BaseActivity implements WZStatusCallback, WZCameraView.PreviewStatusListener {
//
//    private final static String TAG = StreamLiveActivity.class.getSimpleName();
//
//    private final static String TAG_DIALOG_PERMISSION = "dialog_permission_tag";
//    private final static String TAG_DIALOG_ERROR = "dialog_error_tag";
//
//    private static String SDK_SAMPLE_APP_LICENSE_KEY = "GOSK-4244-0103-D063-64A0-4CAD";
//    private static final int PERMISSIONS_REQUEST_CODE = 0x1;
//    private static final int PERMISSIONS_SETTING_CODE = 0x2;
//
//    private final static String[] CAMERA_CONFIG_PREFS_SORTED = new String[]{"wz_video_enabled"
//            , "wz_video_frame_size", "wz_video_preset"};
//
//    @BindView(R.id.stream_camera)
//    protected WZCameraView cameraView;
//    @BindView(R.id.stream_btn_volume)
//    protected ImageView btnVolume;
//    @BindView(R.id.stream_btn_start)
//    protected ImageView btnStart;
//    @BindView(R.id.stream_top_switch)
//    protected ImageView btnSwitch;
//    @BindView(R.id.stream_tx_toast)
//    protected CustomFontTextView startToast;
//    protected WZAudioDevice mWZAudioDevice = null;
//
//    private static Object sBroadcastLock = new Object();
//    private static boolean sBroadcastEnded = true;
//
//    protected static WowzaGoCoder sGoCoderSDK = null;
//    protected WZBroadcast mWZBroadcast = null;
//    protected WZBroadcastConfig mWZBroadcastConfig = null;
//    protected int mWZNetworkLogLevel = WZLog.LOG_LEVEL_DEBUG;
//
//    protected String[] mRequiredPermissions = {};
//    protected String[] mShouldSetPermissions, mRequestPermissions;
//    protected boolean mPermissionsGranted = false;
//    private boolean hasPermissions = false;
//    private boolean hasResumed = false;//是否已经调用过至少一次onResume
//    private boolean calledPermissionInResult = false;//是否在权限回调中调用了显示diaolog
//    private boolean mDevicesInitialized = false;
//
//    private TimerViewHelper<CustomFontTextView> timerViewHelper;
//
//    private Handler handler;
//
//    private AlertDialogFragment permissionDialog;
//    private AlertDialogFragment errorDialog;
//
//    private SharedPreferences.OnSharedPreferenceChangeListener mPrefsChangeListener = null;
//    private LiveAdvanceInfo advanceInfo;
//    private boolean isVoice = false;
//
//    @Override
//    protected void onCreate(Bundle savedInstanceState) {
//        super.onCreate(savedInstanceState);
//
//        advanceInfo = (LiveAdvanceInfo) getIntent().getSerializableExtra("data");
//        String key = getIntent().getStringExtra("key");
//        if (!TextUtils.isEmpty(key)) {
//            SDK_SAMPLE_APP_LICENSE_KEY = key;
//        }
//        if (advanceInfo == null) {
//            Toast.makeText(this, "直播配置信息错误，请联系管理员!", Toast.LENGTH_SHORT).show();
//            finish();
//            return;
//        }
//        timerViewHelper = new TimerViewHelper<>(startToast);
//        DefaultTextTimerCallback<CustomFontTextView> callback =
//                new DefaultTextTimerCallback<>(getString(R.string.click_btn_to_start_stream));
//        timerViewHelper.setCallback(callback);
//
//        handler = new Handler();
//
//        mRequiredPermissions = new String[]{
//                Manifest.permission.CAMERA,
//                Manifest.permission.RECORD_AUDIO
//        };
//
//        hasPermissions = hasDevicePermissionToAccess();
//
//        JLog.e(" has permission " + hasPermissions);
//
//        if (hasPermissions) {
//            initWowza();//要报错
//        }
//
//    }
//
//    @Override
//    protected void initInject() {
//        setContentView(R.layout.activity_stream_live);
//        ButterKnife.bind(this);
//    }
//
//    @Override
//    protected void onResume() {
//        super.onResume();
//        JLog.e("has resumed=" + hasResumed);
//        if (hasResumed) {
//            if (calledPermissionInResult) {
//                calledPermissionInResult = false;
//            } else {
//                if (permissionDialog == null || !permissionDialog.isAdded()) {
//                    hasPermissions = hasDevicePermissionToAccess();
//                }
//            }
//        } else {
//            hasResumed = true;
//        }
//        JLog.e("has permissions=" + hasPermissions);
//        if (hasPermissions) {
//            if (sGoCoderSDK == null) {
//                initWowza();//目前此方法会报错，先注释掉，等解决方案
//            }
////            if (cameraView != null) {
////                cameraView.onResume();
////            }
//            if (!mDevicesInitialized) {
//                initGoCoderDevices();
//            }
//            initCamera();
//        }
////        if (ini)
//    }
//
//    @Override
//    protected void onPause() {
//        if (mWZBroadcast != null && mWZBroadcast.getStatus().isRunning()) {
//            endBroadcast(true);
//        }
//        super.onPause();
//        if (cameraView != null) {
//            cameraView.onPause();
//        }
//
//        if (mPrefsChangeListener != null) {
//            SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
//            sharedPrefs.unregisterOnSharedPreferenceChangeListener(mPrefsChangeListener);
//        }
//
//        if (cameraView != null && cameraView.isPreviewing())
//            cameraView.stopPreview();
//    }
//
//    @Override
//    protected void onDestroy() {
//        if (timerViewHelper != null) {
//            timerViewHelper.onDestory();
//        }
//        super.onDestroy();
//    }
//
//    @Override
//    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);
//        if (requestCode == PERMISSIONS_SETTING_CODE) {
//            hasPermissions = PermissionUtils.checkPermissions(this, mShouldSetPermissions) == null;
//            JLog.e("has permission " + hasPermissions);
//            if (hasPermissions) {
//                mRequestPermissions = null;
//                mShouldSetPermissions = null;
//                //// TODO: 2017/7/26 做些神马
//
//            } else {
//                toast("未获取到足够的权限");
//            }
//        }
//    }
//
//    @Override
//    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
//        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
//        JLog.e("requescode=" + requestCode);
//        if (requestCode == PERMISSIONS_REQUEST_CODE) {
//            ArrayList<String> list = new ArrayList<>();
//            String[] ss = PermissionUtils.checkPermissions(this, list, mRequestPermissions);
////            if (list.size() > 0) {
////                if (ss)
////            }
//
//            calledPermissionInResult = true;
//            String str = "\n";
//            if (ss != null) {
//                boolean b = list.size() > 0 && ss.length == list.size();
//                if (mShouldSetPermissions != null) {
////                    if (b) {
////                        showPermissionDialog(getString(R.string.get_permission_with)+"\n" + Manifest.permission.CAMERA + "\n" + Manifest.permission.RECORD_AUDIO, false);
////                    }else {
//                    str = getString(R.string.get_permission_with) + "\n\n相机(摄像头)权限\n麦克风权限";
//                    JLog.e("will show Dialog");
//                    showPermissionDialog(str, false);
////                    }
////                    PermissionUtils.toSetting(this, PERMISSIONS_SETTING_CODE);
//                } else {
//                    str = str + "\n";
//                    for (int i = 0; i < ss.length; i++) {
//                        if (Manifest.permission.CAMERA.equals(ss[i])) {
//                            str = str + "相机(摄像头)权限\n";
//                        } else {
//                            str = str + "麦克风权限\n";
//                        }
//                    }
//                    JLog.e("will show Dialog");
//                    showPermissionDialog(getString(R.string.get_permission_with) + str, b);
//                }
//            } else {
//                if (mShouldSetPermissions != null) {
//                    if (Manifest.permission.CAMERA.equals(mShouldSetPermissions[0])) {
//                        str = getString(R.string.get_permission_with) + "\n\n相机(摄像头)权限";
//                    } else {
//                        str = getString(R.string.get_permission_with) + "\n\n麦克风权限";
//                    }
//                    JLog.e("will show Dialog");
//                    showPermissionDialog(str, false);
//                } else {
//                    hasPermissions = true;
//                    calledPermissionInResult = false;
//                }
//            }
//        }
//    }
//
//    @Override
//    public void onWZStatus(WZStatus wzStatus) {
//        handler.post(new ORunnable<WZStatus>(wzStatus) {
//            @Override
//            public void run() {
//                if (t.isReady()) {
//                    // Keep the screen on while the broadcast is active
//                    getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
//
//                    // Since we have successfully opened up the server connection, store the connection info for auto complete
////                    GoCoderSDKPrefs.storeHostConfig(PreferenceManager.getDefaultSharedPreferences(GoCoderSDKActivityBase.this), mWZBroadcastConfig);
//                } else if (t.isIdle()) {
//                    // Clear the "keep screen on" flag
//                    getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
//                }
//
//            }
//        });
//    }
//
//    @Override
//    public void onWZError(WZStatus wzStatus) {
//        handler.post(new ORunnable<WZStatus>(wzStatus) {
//            @Override
//            public void run() {
//                WZLog.error(TAG, t.getLastError());
//            }
//        });
//    }
//
//    @Override
//    public void onWZCameraPreviewStarted(WZCamera wzCamera, WZSize wzSize, int i) {
//        // Briefly display the video configuration
//        Toast.makeText(this, mWZBroadcastConfig.getLabel(true, true, false, true), Toast.LENGTH_LONG).show();
//    }
//
//    @Override
//    public void onWZCameraPreviewStopped(int cameraId) {
//    }
//
//    @Override
//    public void onWZCameraPreviewError(WZCamera wzCamera, WZError wzError) {
//        displayErrorDialog(wzError);
//    }
//
//
//    @OnClick(value = {R.id.stream_btn_start, R.id.stream_btn_volume, R.id.stream_top_switch, R.id.stream_top_close})
//    public void click(View v) {
//        switch (v.getId()) {
//            case R.id.stream_btn_start:
//                startClick();
//                break;
//            case R.id.stream_top_switch:
//                onSwitchCamera(v);
//                break;
//            case R.id.stream_top_close:
//                endBroadcast();
//                finish();
//                break;
//            case R.id.stream_btn_volume:
//                if (mWZBroadcastConfig != null) {
//                    mWZBroadcastConfig.setAudioEnabled(!isVoice);
//                }
//                if (mWZAudioDevice != null) {
//                    mWZAudioDevice.setAudioEnabled(!isVoice);
//                }
//                if (isVoice) {
//                    btnVolume.setImageResource(R.mipmap.icon_living_shot_volume);
//                } else {
//                    btnVolume.setImageResource(R.mipmap.icon_living_volume_open);//TODO change pic
//                }
//                isVoice = !isVoice;
//                break;
//        }
//    }
//
//    private void startClick() {
////        JLog.e("start click runing is "+b);
////        if (timerViewHelper.isRunning()) {
////
////        } else {
////
////        }
//
//        if (mWZBroadcast == null) return;
//
//        if (mWZBroadcast.getStatus().isIdle()) {
//            mWZBroadcast.setLogLevel(mWZNetworkLogLevel);
//            if (!mWZBroadcastConfig.isAudioEnabled()) {
//                Toast.makeText(this, "The audio stream is currently turned off", Toast.LENGTH_LONG).show();
//                btnVolume.setImageResource(R.mipmap.icon_living_volume_open);
//                isVoice = true;
//            } else {
//                btnVolume.setImageResource(R.mipmap.icon_living_shot_volume);//TODO change pic
//                isVoice = false;
//            }
//            if (mWZBroadcastConfig.isVideoEnabled()) {
//                WZStreamingError configError = startBroadcast();
//                if (configError != null) {
////                    if (mStatusView != null)
////                        mStatusView.setErrorMessage(configError.getErrorDescription());
//                    timerViewHelper.stopTimer();
//                    startToast.setText(configError.getErrorDescription());
//                } else {
//                    timerViewHelper.startTimer();
//                    btnStart.setImageResource(R.mipmap.icon_living_shot_shoting);
//                }
//            } else {
//                Toast.makeText(this, "The video stream is currently turned off", Toast.LENGTH_LONG).show();
//            }
//        } else {
//            endBroadcast();
//            timerViewHelper.stopTimer();
//            btnStart.setImageResource(R.mipmap.icon_living_shot);
//        }
//    }
//
//    private void initWowza() {
//        if (sGoCoderSDK == null) {
//            // Enable detailed logging from the GoCoder SDK
//            WZLog.LOGGING_ENABLED = true;
//
//            // Initialize the GoCoder SDK
//            sGoCoderSDK = WowzaGoCoder.init(this, SDK_SAMPLE_APP_LICENSE_KEY);
//
//            if (sGoCoderSDK == null) {
//                WZLog.error(TAG, WowzaGoCoder.getLastError());
//            }
//        }
//
//        if (sGoCoderSDK != null) {
//            // Create a new instance of the preferences mgr
////            mGoCoderSDKPrefs = new GoCoderSDKPrefs();
//
//            // Create an instance for the broadcast configuration
//            if (advanceInfo.getHeight() == 480) {
//                mWZBroadcastConfig = new WZBroadcastConfig(WZMediaConfig.FRAME_SIZE_640x480);
//            } else if (advanceInfo.getHeight() == 720) {
//                mWZBroadcastConfig = new WZBroadcastConfig(WZMediaConfig.FRAME_SIZE_1280x720);
//            } else {
//                mWZBroadcastConfig = new WZBroadcastConfig(WZMediaConfig.FRAME_SIZE_1920x1080);
//            }
//            mWZBroadcastConfig.setVideoBitRate(advanceInfo.getRate());
//
//            // Create a broadcaster instance
//            mWZBroadcast = new WZBroadcast();
////            mWZBroadcast.setLogLevel(WZLog.LOG_LEVEL_DEBUG);
//        }
//    }
//
//    protected void initGoCoderDevices() {
//        if (sGoCoderSDK != null) {
//
//            boolean videoIsInitialized = false;
//            boolean audioIsInitialized = false;
//
//            // Initialize the camera preview
////            hasPermissions=hasDevicePermissionToAccess();
//            if (hasPermissions) {
//                if (cameraView != null) {
//                    WZCamera availableCameras[] = cameraView.getCameras();
//                    // Ensure we can access to at least one camera
//                    if (availableCameras.length > 0) {
//                        // Set the video broadcaster in the broadcast config
//                        mWZBroadcastConfig.setVideoBroadcaster(cameraView);
//                        videoIsInitialized = true;
//                    } else {
////                        mStatusView.setErrorMessage("Could not detect or gain access to any cameras on this device");
//                        mWZBroadcastConfig.setVideoEnabled(false);
//                    }
//                } else {
//                    mWZBroadcastConfig.setVideoEnabled(false);
//                }
//            }
//
////            if(this.hasDevicePermissionToAccess(Manifest.permission.RECORD_AUDIO)) {
//            // Initialize the audio input device interface
//            mWZAudioDevice = new WZAudioDevice();
//
//            // Set the audio broadcaster in the broadcast config
//            mWZBroadcastConfig.setAudioBroadcaster(mWZAudioDevice);
//            audioIsInitialized = true;
////            }
//
//            if (videoIsInitialized && audioIsInitialized) {
//                mDevicesInitialized = true;
//            }
//        }
//    }
//
//    private void initCamera() {
//        if (sGoCoderSDK != null) {
//            SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
//            if (mWZBroadcastConfig != null) {
//                GoCoderSDKPrefs.updateConfigFromPrefs(sharedPrefs, mWZBroadcastConfig, advanceInfo);
//            }
//            // Update the camera preview display config based on the stored shared preferences
//            cameraView.setCameraConfig(mWZBroadcastConfig);
////            cameraView.setScaleMode(GoCoderSDKPrefs.getScaleMode(sharedPrefs));
//            cameraView.setVideoBackgroundColor(WZColor.DARKGREY);
//
//            // Setup up a shared preferences change listener to update the camera preview
//            // as the related preference values change
//            mPrefsChangeListener = new SharedPreferences.OnSharedPreferenceChangeListener() {
//                @Override
//                public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String prefsKey) {
//                    if (cameraView != null && Arrays.binarySearch(CAMERA_CONFIG_PREFS_SORTED, prefsKey) != -1) {
//                        // Update the camera preview display frame size
//                        WZSize currentFrameSize = cameraView.getFrameSize();
//                        int prefsFrameWidth = sharedPreferences.getInt("wz_video_frame_width", currentFrameSize.getWidth());
//                        int prefsFrameHeight = sharedPreferences.getInt("wz_video_frame_height", currentFrameSize.getHeight());
//                        WZSize prefsFrameSize = new WZSize(prefsFrameWidth, prefsFrameHeight);
//                        if (!prefsFrameSize.equals(currentFrameSize))
//                            cameraView.setFrameSize(prefsFrameSize);
//
//                        // Toggle the camera preview on or off
//                        boolean videoEnabled = sharedPreferences.getBoolean("wz_video_enabled", mWZBroadcastConfig.isVideoEnabled());
//                        if (videoEnabled && !cameraView.isPreviewing()) {
//                            cameraView.startPreview();
//                        } else if (!videoEnabled && cameraView.isPreviewing()) {
//                            cameraView.stopPreview();
//                        }
//                    }
//                }
//            };
//
//            sharedPrefs.registerOnSharedPreferenceChangeListener(mPrefsChangeListener);
//
//            if (mWZBroadcastConfig.isVideoEnabled()) {
//                // Start the camera preview display
//                if (cameraView.isPreviewPaused())
//                    cameraView.onResume();
//                else
//                    cameraView.startPreview();
//            } else {
//                Toast.makeText(this, "The video stream is currently turned off", Toast.LENGTH_LONG).show();
//            }
//        }
//    }
//
//    /**
//     * Display an alert dialog containing an error message.
//     *
//     * @param errorMessage The error message text
//     */
//    protected void displayErrorDialog(String errorMessage) {
//        // Log the error message
//        WZLog.error(TAG, errorMessage);
//
//        if (errorDialog == null) {
//            errorDialog = new AlertDialogFragment();
//            errorDialog.setTitleStr(getString(R.string.wrong));
//            errorDialog.setOkStrRes(R.string.ok);
//        }
//        errorDialog.setMsgStr(errorMessage);
//
//        // Display an alert dialog containing the error message
////        AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(this, R.style.myDialog));
////        //AlertDialog.Builder builder = new AlertDialog.Builder(this, android.R.style.Theme_Material_Dialog_Alert);
////        builder.setMessage(errorMessage)
////                .setTitle(R.string.dialog_title_error);
////        builder.setPositiveButton(R.string.dialog_button_close, new DialogInterface.OnClickListener() {
////            public void onClick(DialogInterface dialog, int id) {
////                dialog.dismiss();
////            }
////        });
//
////        builder.create().show();
//        safeShowDialog(errorDialog, TAG_DIALOG_ERROR);
//    }
//
//    /**
//     * Display an alert dialog containing the error message for
//     * an error returned from the GoCoder SDK.
//     *
//     * @param goCoderSDKError An error returned from the GoCoder SDK.
//     */
//    protected void displayErrorDialog(WZError goCoderSDKError) {
//        displayErrorDialog(goCoderSDKError.getErrorDescription());
//    }
//
//    private synchronized void showPermissionDialog(String msg, boolean canRequest) {
//        if (permissionDialog == null) {
//            permissionDialog = new AlertDialogFragment();
//            permissionDialog.setCancleStrRes(R.string.got_it);
//            permissionDialog.setOkStrRes(R.string.go_setting);
//            permissionDialog.setMsgGravity(Gravity.LEFT);
//            permissionDialog.setOnViewClick(new AlertDialogFragment.OnViewClick() {
//                @Override
//                public boolean onViewClick(View view, int viewItem, int mode) {
//                    if (viewItem == AlertDialogFragment.VIEW_ITEM_OK) {
//                        if (mode == 1) {
//                            ActivityCompat.requestPermissions(StreamLiveActivity.this, mRequestPermissions, PERMISSIONS_REQUEST_CODE);
//                        } else {
//                            PermissionUtils.toSetting(StreamLiveActivity.this, PERMISSIONS_SETTING_CODE);
//                        }
//                    }
//                    return true;
//                }
//            });
//        }
//        permissionDialog.setMsgStr(msg);
//        permissionDialog.setModeTag(canRequest ? 1 : 0);
//        JLog.e("added=" + permissionDialog.isAdded() + "  detached=" + permissionDialog.isDetached()
//                + "  resumed=" + permissionDialog.isResumed() + "  layout=" + permissionDialog.isInLayout()
//                + "  removing=" + permissionDialog.isRemoving() + "  visible=" + permissionDialog.isVisible());
//        try {
//            safeShowDialog(permissionDialog, TAG_DIALOG_PERMISSION);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }
//
//    /**
//     * Click handler for the switch camera button
//     */
//    public void onSwitchCamera(View v) {
//        if (cameraView == null) return;
//
////        btnSwitch.setState(false);
//        btnSwitch.setEnabled(false);
//
//        WZCamera c = cameraView.getCamera();
//        JLog.e("old torch " + c.hasCapability(WZCamera.TORCH));
//        WZCamera newCamera = cameraView.switchCamera();
//        if (newCamera != null) {
//            if (newCamera.hasCapability(WZCamera.FOCUS_MODE_CONTINUOUS))
//                newCamera.setFocusMode(WZCamera.FOCUS_MODE_CONTINUOUS);
//
//            boolean hasTorch = newCamera.hasCapability(WZCamera.TORCH);
////            JLog.e("new torch "+hasTorch);
////            if (hasTorch) {
////                mBtnTorch.setState(newCamera.isTorchOn());
////                btnSwitch.setEnabled(true);
////            }
//            handler.postDelayed(new Runnable() {//防止切换过于频繁
//                @Override
//                public void run() {
//                    btnSwitch.setEnabled(true);
//                }
//            }, 1000);
//        }
//    }
//
//    protected boolean hasDevicePermissionToAccess() {
//        boolean result = false;
//        JLog.e("in");
//        ArrayList<String> canre = new ArrayList<>();
//        String[] ss = PermissionUtils.checkPermissions(this, canre, mRequiredPermissions);
//        result = ss == null;
//        if (canre.size() > 0) {
//            String[] req = new String[canre.size()];
//            req = canre.toArray(req);
//            mRequestPermissions = req;
//            ActivityCompat.requestPermissions(this, req, PERMISSIONS_REQUEST_CODE);
//            if (ss != null && ss.length > canre.size()) {
//                JLog.e("ss length=" + ss.length + "   size=" + canre.size());
//                String str = canre.get(0);
//                if (Manifest.permission.CAMERA.equals(str)) {
//                    mShouldSetPermissions = new String[]{Manifest.permission.CAMERA};
//                } else {
//                    mShouldSetPermissions = new String[]{Manifest.permission.RECORD_AUDIO};
//                }
//            }
//        } else {
//            if (ss != null) {
//                mShouldSetPermissions = ss;
//                String str = "\n";
//                for (int i = 0; i < ss.length; i++) {
//                    if (Manifest.permission.CAMERA.equals(ss[i])) {
//                        str = str + "相机(摄像头)权限\n";
//                    } else {
//                        str = str + "麦克风权限\n";
//                    }
//                }
//                JLog.e("will show Dialog");
//                showPermissionDialog(getString(R.string.get_permission_with) + "\n" + str, false);
//            }
//        }
//
////                result = (mRequiredPermissions.length > 0 ? WowzaGoCoder.hasPermissions(this, mRequiredPermissions) : true);
////                if (!result && !hasPermissions) {
////                    WZLog.debug("ACCESS[hasDevicePermissionToAccess()-3]::requestPermissions");
////
////                    hasPermissions = true;
////                }
//        return result;
//    }
//
//    protected synchronized WZStreamingError startBroadcast() {
//        WZStreamingError configValidationError = null;
//
//        if (mWZBroadcast.getStatus().isIdle()) {
//
//            // Set the detail level for network logging output
////            mWZBroadcast.setLogLevel(mWZNetworkLogLevel);
//
//            //
//            // An example of adding metadata values to the stream for use with the onMetadata()
//            // method of the IMediaStreamActionNotify2 interface of the Wowza Streaming Engine Java
//            // API for server modules.
//            //
//            // See http://www.wowza.com/resources/serverapi/com/wowza/wms/stream/IMediaStreamActionNotify2.html
//            // for additional usage information on IMediaStreamActionNotify2.
//            //
//
//            // Add stream metadata describing the current device and platform
//            WZDataMap streamMetadata = new WZDataMap();
//            streamMetadata.put("androidRelease", new WZDataItem(Build.VERSION.RELEASE));
//            streamMetadata.put("androidSDK", new WZDataItem(Build.VERSION.SDK_INT));
//            streamMetadata.put("deviceProductName", new WZDataItem(Build.VERSION.SDK_INT));
//            streamMetadata.put("deviceManufacturer", new WZDataItem(Build.MANUFACTURER));
//            streamMetadata.put("deviceModel", new WZDataItem(Build.MODEL));
//
//            mWZBroadcastConfig.setStreamMetadata(streamMetadata);
//            //
//            // An example of adding query strings for use with the getQueryStr() method of
//            // the IClient interface of the Wowza Streaming Engine Java API for server modules.
//            //
//            // See http://www.wowza.com/resources/serverapi/com/wowza/wms/client/IClient.html#getQueryStr()
//            // for additional usage information on getQueryStr().
//            //
//            try {
//                PackageInfo pInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
//
//                // Add query string parameters describing the current app
//                WZDataMap connectionParameters = new WZDataMap();
//                connectionParameters.put("appPackageName", new WZDataItem(pInfo.packageName));
//                connectionParameters.put("appVersionName", new WZDataItem(pInfo.versionName));
//                connectionParameters.put("appVersionCode", new WZDataItem(pInfo.versionCode));
//
//                mWZBroadcastConfig.setConnectionParameters(connectionParameters);
//
//            } catch (PackageManager.NameNotFoundException e) {
//                WZLog.error(TAG, e);
//            }
//
//            WZLog.info(TAG, "=============== Broadcast Configuration ===============\n"
//                    + mWZBroadcastConfig.toString()
//                    + "\n=======================================================");
//
//            configValidationError = mWZBroadcastConfig.validateForBroadcast();
//            if (configValidationError == null) {
//                mWZBroadcast.startBroadcast(mWZBroadcastConfig, this);
//            }
//        } else {
//            WZLog.error(TAG, "startBroadcast() called while another broadcast is active");
//        }
//        return configValidationError;
//    }
//
//    protected synchronized void endBroadcast(boolean appPausing) {
//        if (mWZBroadcast==null){
//            return;
//        }
//        if (!mWZBroadcast.getStatus().isIdle()) {
//            if (appPausing) {
//                // Stop any active live stream
//                sBroadcastEnded = false;
//                mWZBroadcast.endBroadcast(new WZStatusCallback() {
//                    @Override
//                    public void onWZStatus(WZStatus wzStatus) {
//                        synchronized (sBroadcastLock) {
//                            sBroadcastEnded = true;
//                            sBroadcastLock.notifyAll();
//                        }
//                    }
//
//                    @Override
//                    public void onWZError(WZStatus wzStatus) {
//                        WZLog.error(TAG, wzStatus.getLastError());
//                        synchronized (sBroadcastLock) {
//                            sBroadcastEnded = true;
//                            sBroadcastLock.notifyAll();
//                        }
//                    }
//                });
//
//                while (!sBroadcastEnded) {
//                    try {
//                        sBroadcastLock.wait();
//                    } catch (InterruptedException e) {
//                    }
//                }
//            } else {
//                mWZBroadcast.endBroadcast(this);
//            }
//        } else {
//            WZLog.error(TAG, "endBroadcast() called without an active broadcast");
//        }
//    }
//
//    protected synchronized void endBroadcast() {
//        endBroadcast(false);
//    }
//
//
//    private static abstract class ORunnable<T> implements Runnable {
//
//        protected T t;
//
//        public ORunnable(T t) {
//            this.t = t;
//        }
//    }
//
//    private WZBroadcastConfig parseConfig(String address, WZBroadcastConfig config) {
//
//        if (TextUtils.isEmpty(address)) {
//            return null;
//        }
//
//        return config;
//
//    }
//
//}
